package com.nondo.rdp.auth.repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.nondo.rdp.auth.domain.UserMessage;
import com.nondo.rdp.core.common.StatusConstant;

public interface UserMessageRepository extends JpaRepository<UserMessage, Long>,
		JpaSpecificationExecutor<UserMessage> {
	@Query("select a from UserMessage a where a.id=:id and delFlag = '"
			+ StatusConstant.DEL_FLAG_NORMAL + "'")
	Optional<UserMessage> findOne(@Param("id") int id);

	@Modifying
	@Query("update UserMessage set delFlag='" + StatusConstant.DEL_FLAG_DELETE + "' where id = ?1")
	void deleteById(Long id);

	UserMessage save(UserMessage userMessage);

	@Modifying
	@Query("update UserMessage um set um.isRead=1 where um.message.id = ? and um.user.id = ?")
	void update(Long mid, Long uid);

	@Query("select count(a.id) from UserMessage a, Message b where a.message.id=b.id and a.user.id = ? and a.isRead=0" 
			+ " and a.delFlag = '" + StatusConstant.DEL_FLAG_NORMAL + "'"
			+ " and b.delFlag = '"+ StatusConstant.DEL_FLAG_NORMAL + "'")
	int count(Long uid);

}
